package com.cykj.arresterservice.handler;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;
import org.quickserver.net.server.ClientBinaryHandler;
import org.quickserver.net.server.ClientHandler;

import com.cykj.arresterservice.command.ArresterCommand;
import com.cykj.arresterservice.command.ICommandParse;
import com.cykj.util.ArrayCopyUtil;
import com.cykj.util.CRCUtil;
import com.cykj.util.PropertiesUtil;

public class ArresterBinaryHandler implements ClientBinaryHandler {
	
	public static final Logger logger = Logger.getLogger(ArresterBinaryHandler.class);
	
/*	public static final PropertiesUtil propertiesUtil =  new PropertiesUtil("config.properties");
	public static final String jdbcServer = propertiesUtil.readProperty("jdbc_server");
	public static final String jdbcPort = propertiesUtil.readProperty("jdbc_port");
	public static final String jdbcDbname = propertiesUtil.readProperty("jdbc_dbname");
	public static final String jdbcUsername = propertiesUtil.readProperty("jdbc_username");
	public static final String jdbcPassword = propertiesUtil.readProperty("jdbc_password");
	
	public static final String nariServer = propertiesUtil.readProperty("nari_server");*/
	
	private ICommandParse commandParse = new ArresterCommand();
	
	public void gotConnected(ClientHandler handler) throws IOException {
		logger.info("connected:" + handler.getSocket().getInetAddress());
	}
	
	public void lostConnection(ClientHandler handler) {
		logger.info("lostConnection:" + handler.getSocket().getInetAddress());
	}
	
	public void closingConnection(ClientHandler handler) {
		logger.info("closingConnection:" + handler.getSocket().getInetAddress());
	}

	public void handleBinary(ClientHandler handler, byte command[]) throws SocketTimeoutException, IOException {
    
		logger.info("client[" + handler.getSocket().getInetAddress() + "]:" + byte2HexString(command));
		
		commandParse.parseCommand(handler, command);
	}
	
	private String byte2HexString(byte[] buffer)
    {
    	String s = "";
        for(byte b : buffer) {
        	
        	String hexOutput = String.format("%02X", b);
        	
        	s += hexOutput;
        }
    	
    	return s;
    }
}
